package com.partners.service.Impl;

import com.partners.configure.SendCode;
import com.partners.constant.ErrorMessageEnum;
import com.partners.dao.dto.LoginInputDTO;
import com.partners.dao.basic.ConfigDao;
import com.partners.dao.basic.FansDao;
import com.partners.dao.basic.PointsLogDao;
import com.partners.dao.basic.UserDao;
import com.partners.dao.bo.ConfigDO;
import com.partners.dao.bo.FansDO;
import com.partners.dao.bo.PointsLogDO;
import com.partners.dao.bo.UserDO;
import com.partners.model.BusinessException;
import com.partners.model.ValidCodeModel;
import com.partners.service.FansService;
import com.partners.service.LoginService;
import com.partners.utils.TimestampUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liangyongle
 * @date 2018-12-14
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Resource
    private UserDao userDao;

    @Resource
    private SendCode sendCode;

    @Resource
    private PointsLogDao pointsLogDao;

    @Resource
    private ConfigDao configDao;

    @Resource
    private FansDao fansDao;

    @Resource
    private FansService fansService;

    @Override
    public Map<String,Object> checkLogin(LoginInputDTO loginInputDTO) {
        //检查当前用户信息
        UserDO userDO = userDao.selectByPrimaryKey(loginInputDTO.getId());
        if(userDO == null){
            throw BusinessException.of(ErrorMessageEnum.USER_NOT_EXIST);
        }
        Map<String,Object> result = new HashMap<>();
        //1.验证验证码
        Long phones = loginInputDTO.getPhone();
        String phone = phones.toString();
        ValidCodeModel validCodeModel = sendCode.getValidCodeModel(phone);
        //验证手机是否有验证码
        if(validCodeModel == null){
            throw BusinessException.of(ErrorMessageEnum.CODE_IS_ERROR);
        }
        String validCode = validCodeModel.getCode();
        if(validCode ==null){
            throw BusinessException.of(ErrorMessageEnum.CODE_IS_ERROR);
        }
        Integer code = loginInputDTO.getVerifyCode();
        log.info("coce:{}",validCode);

        //验证手机验证码
        if(!validCode.equals(code.toString())){
            throw BusinessException.of(ErrorMessageEnum.CODE_IS_ERROR);
        }
        //验证是否过期
        Integer nowTime = TimestampUtils.timestamp();
        if(nowTime > validCodeModel.getOverTime()){
            throw BusinessException.of(ErrorMessageEnum.CODE_OVER_TIME);
        }

        Integer userId = userDao.getUserInfoByPhone(loginInputDTO.getPhone(),0);
        if(userId == null){
            throw BusinessException.of(ErrorMessageEnum.LOGIN_ERROR);
        }
//        UserDO user = new UserDO();
//        user.setId(loginInputDTO.getId());
//        user.setOpenid(loginInputDTO.getOpenid());
//        userDao.updateByPrimaryKeySelective(user);
        //增加积分
        ConfigDO configDO = configDao.selectByPrimaryKey(1);
        if(configDO.getIsaward() == 1){
            Integer points = configDO.getPints();
            Byte source = 1;
            //查询需要添加积分的人
            Integer pid = userDO.getPid();
            if(pid !=0){
                UserDO puser = userDao.selectByPrimaryKey(pid);
                PointsLogDO pointsLog = new PointsLogDO();
                pointsLog.setUid(pid);
                pointsLog.setTitle(puser.getName()+"发展合伙人【"+userDO.getName()+"】获得积分");
                pointsLog.setOrderid(loginInputDTO.getId());
                pointsLog.setPoint(points);
                pointsLog.setAddtime(TimestampUtils.timestamp());
                pointsLog.setSource(source);
                pointsLogDao.insertSelective(pointsLog);
            }
        }
        //获取粉丝信息

        //更新粉丝信息
        FansDO fans = fansDao.getFansInfoByOpenId(loginInputDTO.getOpenid());
        FansDO fansInfo = new FansDO();
        byte types = 2;
        fansInfo.setType(types);
        fansInfo.setFanid(fans.getFanid());
        fansInfo.setUserId(loginInputDTO.getId());
        fansDao.updateByPrimaryKeySelective(fansInfo);
        //重新更新粉丝缓存信息
        Object fansInfos = fansService.getFansInfoByOpenId(loginInputDTO.getOpenid());
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession();
        session.setAttribute("openId", fansInfos);
        result.put("user_id",userId);
        return result;

    }


    /**
     * 发送验证码
     * @param phone
     * @return
     * @throws
     */
    @Override
    public void sendCode(String phone) {
        ValidCodeModel validCodeModel = sendCode.getValidCodeModel(phone);

        if (validCodeModel == null){
            validCodeModel = sendCode.sendAndGetValidCodeModel(phone);
        }else {
            Integer overTime = validCodeModel.getOverTime();
            if (overTime < TimestampUtils.timestamp()) {
                sendCode.cleanAndGetValidCodeModel(phone);
            } else {
                throw BusinessException.of(ErrorMessageEnum.CODE_IS_SEND);
            }
        }
    }

    /**
     * 获取验证码
     * @param phone
     * @return
     * @throws
     */
    @Override
    public String getValidCode(String phone) {
        ValidCodeModel validCodeModel = sendCode.getValidCodeModel(phone);
        String validCode = validCodeModel.getCode();
        return validCode;

    }
}
